import { Component, OnInit, OnDestroy } from '@angular/core';
import {WebsocketService} from './websocket.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  messagesList = []; // 消息列表
  userList:any; // 用户列表
  Inputmessage: any = '';
  // 当前用户信息
  selfData = {
    clientId: '',
    clientName: '',
    sessionId:'',
    online:''
  };
  // 目标用户信息
  targetSelectData:any = {
    clientId:'',
    clientName:'',
    sessionId:''
  };

  connection_msg: any;
  connection_userlist: any;
  connection_curruser: any;
  
  constructor(private websocketService: WebsocketService) {

  }
  
  ngOnInit(): void {
    this.connection_msg = this.websocketService.getMessages().subscribe(message => {
      // message.date = new Date();
      // message.img = '/assets/images/1.jpg';
      const _messagelist:any = message;
      this.messagesList.push(_messagelist);
      this.msgScroll();
    })
    this.connection_userlist = this.websocketService.loadUserList().subscribe(list => {
      const _userlist:any = list;
      this.userList = _userlist.data;
    })

    this.connection_curruser = this.websocketService.loadCurrentUser().subscribe(data => {
      const _data:any = data;
      this.selfData = _data;
    })
  }
  /**
   * 监听消息
   */
  getMessagesFn(){
    
  }

  /**
   * 发送消息
   * @param msg 消息内容
   */
  sendMsFn($event, msg: string) {
    if(msg && $event.keyCode == 13){
      var jsonObject = {
        sourceSessionId: this.selfData.sessionId,
        targetSessionId: this.targetSelectData.sessionId,
        msg: msg,
        clientId: this.targetSelectData.clientId,
        clientName: this.targetSelectData.clientName,
        date: new Date(),
        img: '/assets/images/1.jpg',
        self: true
      };
      this.messagesList.push(jsonObject);
      this.websocketService.sendMessage(jsonObject);
      this.msgScroll();
      this.Inputmessage = '';
    }
  }
  /**
   * 选择要发送消息的对象
   * @param item 选择对象
   */ 
  select(item: any){
    if(item.sessionId!=this.selfData.sessionId){
      this.targetSelectData = {
        clientId: item.clientId,
        clientName: item.clientName,
        sessionId: item.sessionId
      };
    }
  }
  /**
   * 产生随机数函数
   * @param n 
   */
  RndNum(n:number) {
    var rnd = "";
    for(var i=0;i<n;i++)
        rnd+=Math.floor(Math.random()*10);
    return rnd;
  }
  /**
   * 滚动到底部
   */
  msgScroll(){
    setTimeout(function () {
      var _el = document.getElementById('message-con');
      // _el.scrollTop = _el.scrollHeight;
      _el.scrollTop = _el.scrollHeight - _el.clientHeight;
    }, '100');
  }
  /**
   * 组件注销
   */
  ngOnDestroy() {
    this.connection_msg.unsubscribe();
    this.connection_userlist.unsubscribe();
    this.connection_curruser.unsubscribe();
   }
}
